import pygame
from pygame.locals import *
import random,sys,time

#放置玩家飞机
class Players(object):
    """玩家"""
    def __init__(self,screen_temp):
        self.x = 200
        self.y = 450
        self.screen = screen_temp
        self.image = pygame.image.load("./images/me.png")

        self.bullet_list = []#储存并发射出去的子弹对象引用
        self.destroy_images = []
        self.image_num = 0
        self.image_index = 0
        self.active = True#用以判断飞机们的状态
        self.delay = 100
    def display(self,EnemyPlane):
        """绘制玩家飞机"""
        #遍历移动子弹
        for bullet in self.bullet_list:
            bullet.display()
            if bullet.move():#子弹越界则删除
                self.bullet_list.remove(bullet)
        if self.active:#检验飞机是否存活
            self.screen.blit(self.image,(self.x,self.y))
        else:
            self.screen.blit(self.destroy_images[self.image_index],(self.x,self.y))#否，绘制爆炸
            self.image_num += 1
            if self.image_num == 10:#一张图片显示7帧
                self.image_num = 0
                self.image_index += 1#切换图片
            if self.image_index >2:
                print("GAMEOVER")
                time.sleep(1)
                sys.exit()
    def move_left(self):
        """飞机左移"""
        self.x -= 5
        if self.x <= -35:
            self.x = -35

    def move_right(self):
        """飞机右移"""
        self.x += 5
        if self.x >= 441:
            self.x = 441

    def move_up(self):
        """飞机上移"""
        self.y -= 5
        if self.y <= 0:
            self.y = 0

    def move_down(self):
        """飞机下移"""
        self.y += 5
        if self.y >= 492:
            self.y = 492

    def file(self):
        """子弹发射函数，采用delay参数限制子弹连续、快速的发射"""
        self.delay -= 1
        if not self.delay:
            self.delay = 100
        if not (self.delay % 5):
            self.bullet_list.append(PBullet(self.screen,self.x,self.y))

    def cherk(self,x,y):
        if self.x+15<int(x)<self.x+91 and self.y+18<int(y)<self.y+58:

            self.destroy_images.append(pygame.image.load("./images/bomb1.png"))
            self.destroy_images.append(pygame.image.load("./images/bomb2.png"))
            self.destroy_images.append(pygame.image.load("./images/bomb3.png"))
            self.active = False

#创建子弹类
class PBullet(object):
    """玩家子弹类"""
    def __init__(self,screen_temp,x,y):
        self.x = x + 53
        self.y = y
        self.screen = screen_temp
        self.image = pygame.image.load("./images/pd.png")

    def display(self):
        """绘制玩家子弹"""
        self.screen.blit(self.image,(self.x,self.y))

    def move(self):
        self.y -= 10
        if self.y <= -20:
            return True

class Embullet(object):
    """敌人子弹类"""
    def __init__(self,screen_temp,x,y):
        self.x = x + 58
        self.y = y + 65
        self.screen = screen_temp
        self.image = pygame.image.load("./images/pd.png")

    def display(self):
        """绘制敌人子弹"""
        self.screen.blit(self.image,(self.x,self.y))

    def move(self):
        self.y += 10
        if self.y>568:
            return True


#放置敌机
class EnemyPlane(object):
    """敌机1类"""
    def __init__(self,screen_temp):
        self.x = random.randrange(-35,441,68)
        self.y = -80
        self.screen = screen_temp
        self.image = pygame.image.load("./images/e"+str(random.choice(range(3)))+".png")

        self.embullet = []
        self.delay = 100
        self.destroy_images = []
        self.image_num = 0
        self.image_index = 0
        self.active = True  # 用以判断飞机们的状态

    def display(self,player):
        """绘制敌机"""

        self.delay -= 1
        if not self.delay:
            self.delay = 100
        if not (self.delay % 10):
            self.embullet.append(Embullet(self.screen, self.x, self.y))
        for embullet in self.embullet:
            embullet.display()
            embullet.move()
            player.cherk(embullet.x, embullet.y)
        if self.active:
            self.screen.blit(self.image, (self.x, self.y))
        else:
            self.screen.blit(self.destroy_images[self.image_index],(self.x,self.y))#否，绘制爆炸
            self.image_num += 1
            if self.image_num == 10:#一张图片显示7帧
                self.image_num = 0
                self.image_index += 1#切换图片
            if self.image_index >2:
                return True

    def move(self,player):
        self.y += 4
        #遍历所有子弹，并执行碰撞检测
        for bo in player.bullet_list:
            if self.x + 15 < bo.x < self.x + 91 and self.y + 18 < bo.y < self.y + 58:
                self.destroy_images.append(pygame.image.load("./images/bomb1.png"))
                self.destroy_images.append(pygame.image.load("./images/bomb2.png"))
                self.destroy_images.append(pygame.image.load("./images/bomb3.png"))
                self.active = False
        if self.y >= 568:
            return True




#键盘控制函数
def key_control(player):
    """键盘控制函数"""
    #执行推出操作
    for event in pygame.event.get():
        if event.type == QUIT:
            print("exit()")
            sys.exit()

    #获取按键信息
    pressed_keys = pygame.key.get_pressed()#get_pressed函数可以得到键盘上的所有按键输入信息

    #做判断，并执行对象的操作
    if pressed_keys[K_LEFT] or pressed_keys[K_a]:
        player.move_left()

    elif pressed_keys[K_RIGHT] or pressed_keys[K_d]:
        player.move_right()

    if pressed_keys[K_UP] or pressed_keys[K_w]:
        player.move_up()

    elif pressed_keys[K_DOWN] or pressed_keys[K_s]:
        player.move_down()

    if pressed_keys[K_SPACE]:
        player.file()


#创建游戏主窗口
def main():
    """创建游戏窗口"""
    #1.创建一个游戏窗口:set_mode(分辨率 = （0，0），标志 = 0，深度 = 0)
    screen = pygame.display.set_mode((512,568),0,0)#set_mode设定显示的类型和尺寸，可设定fullscreen版本，默认的是窗口显示
    #相对应还有display.set_caption，设置pygame程序的标题
    #display函数是处理pygame显示方式的函数
    pygame.display.set_caption("打飞机小游戏")

    #2.创建一个游戏背景图片（512*1536）
    background = pygame.image.load("./images/bg2.jpg")#image.load,场景图从本地文件加载
    #image模块，可处理gif,png,jpeg

    m = -968 #初始化背景图片y轴的值

    #3.创建玩家飞机对象
    player = Players(screen)


    #用于延迟
    delay = 100

    #中弹图片索引
    #em_distroy_index = 0
    #4.定义用于存放敌机列表
    enemylist = []#存放敌机
    embullet = []
    while True:
        # 绘制画面
        screen.blit(background, (0, m))#blit，场景的移动，两个参数，左边的参数为场景图，右边为初始位置
        #设置循环，实现无限滚动
        m += 2
        if m >= -200:
            m = -968

        #绘制玩家飞机
        player.display(EnemyPlane)

        #执行键盘控制
        key_control(player)

        clock = pygame.time.Clock()

        #随机绘制敌机
        if random.randint(0,50) == 10:
            enemylist.append(EnemyPlane(screen))
        for em in enemylist:
            if em.display(player):
                enemylist.remove(em)
            em.move(player)
        #遍历敌机并绘制移动,检测失帧，敌机闪烁

        #敌人子弹碰撞检测

        '''if not (delay % 15):  # 延迟发射
            embullet.append(EmBullet(em.screen, em.x, em.y))'''

        delay -= 1
        if not delay:
            delay = 100

        # 更新显示，刷新屏幕
        pygame.display.flip()#update用于只更新屏幕的一部分

        #定时显示，锁屏30帧
        clock.tick(30)

if __name__ == "__main__":
    main()
 